using System.Windows;
using System.Windows.Controls;

namespace Coogle
{
    public class AutoSelectContentBehavior
    {
        public static readonly DependencyProperty EnabledProperty = DependencyProperty.RegisterAttached("Enabled",
                                                                                                        typeof(bool),
                                                                                                        typeof(AutoSelectContentBehavior),
                                                                                                        new UIPropertyMetadata(OnEnabledChanged));

        public static bool GetEnabled(TextBox textBox)
        {
            return (bool)textBox.GetValue(EnabledProperty);
        }

        public static void SetEnabled(TextBox textBox, bool value)
        {
            textBox.SetValue(EnabledProperty, value);
        }

        private static void OnEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var source = d as TextBox;
            if (source == null)
                return;

            if (e.NewValue is bool == false)
                return;

            if ((bool)e.NewValue)
                source.GotFocus += HandleGotFocus;
            else
                source.GotFocus -= HandleGotFocus;
        }

        private static void HandleGotFocus(object sender, RoutedEventArgs e)
        {
            var source = (sender as TextBox);
            if (source != null)
                source.SelectAll();
        }
    }
}